<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use think\Db;
error_reporting(E_ERROR | E_WARNING | E_PARSE);
//获取时间戳的绝对周数（1970年01月01日为第0周）
function get_absolute_week($timestamp = null){
    if ($timestamp==null){
        $timestamp=time();
    }
    $beginWeek = mktime(0,0,0,date("m",$timestamp),date("d",$timestamp)-date("w",$timestamp)+1,date("Y",$timestamp));
    $res = ( $beginWeek - ((4*24*60*60)-(8*60*60)) )/(7*24*60*60);
    return $res;
}
//经纬度转换成三角函数中度分表形式。
function Rad($d){
    return $d * pi() / 180.0;
}
//获取2个地理坐标的距离
function get_distance($lng1,$lat1,$lng2,$lat2){
    $radLat1 = Rad($lat1);
    $radLat2 = Rad($lat2);
    $a = $radLat1 - $radLat2;
    $b = Rad($lng1) - Rad($lng2);
    $s = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)));
    $s = $s *6378.137 ;// EARTH_RADIUS;
    $s = round($s * 10000) / 10000; //输出为公里
    $s=round($s,4);
    return $s;
}

// 应用公共文件
function get_table_comment($table)
{
    $table = Db::name($table)->getTable();
    $re = Db::query("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" . $table . "'");
    $comments = [];
    if (is_array($re)) {
        foreach ($re as $key => $item) {
            if ($item['COLUMN_COMMENT']) {
                $comments[$item['COLUMN_NAME']] = $item;
            } else {
                $item['COLUMN_COMMENT'] = $item['COLUMN_NAME'];
                $comments[$item['COLUMN_NAME']] = $item;
            }

        }
    } else {
        return false;
    }

    return $comments;
}

function get_curl($model, $action, $params = [])
{
    $model_api = Config("model_api.{$model}");
    //$model_api = Config('model_api.'.$model);
    $url = $model_api . "/" . $action;
    $result = \tools\curl\Curl::get($url, $params);
    if (!$result) {
        $result['status'] = false;
        $result['msg'] = '请求失败';
        $result['url'] = $url;
        $result['params'] = $params;
    } else {
        $result = \tools\curl\Curl::json2arr($result);
        if ($result['status'] === false)
            $result['data'] = '数据不存在';
    }
    return $result;
}
function post_curl($model, $action, $params = [])
{
    $model_api = Config("model_api.{$model}");
    //$model_api = Config('model_api.'.$model);
    $url = $model_api . "/" . $action;
    $result = \tools\curl\Curl::post($url, $params);
    if (!$result) {
        $result['status'] = false;
        $result['msg'] = '请求失败';
    } else {
        $result = \tools\curl\Curl::json2arr($result);
        if ($result['status'] === false)
            $result['data'] = '数据不存在';
    }
    return $result;
}

function get_token($length){
    //随机生成指定长度字符串
    $token_str = substr(str_shuffle('abcedfghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, $length);
    return $token_str;
}
/**
 * 生成,保存并返回token
 * @param $user_id  用户id
 */
function save_token($account_id)
{
    //随机生成20位字符串
    $token_str = substr(str_shuffle('abcedfghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 20);

    //token表需要的字段
    $token['account_id'] = $account_id;
    $token['token'] = $token_str;
    $token['expires_in'] = 3600;             //有效期60分钟
    $token['create_time'] = time();
    $token['end_time'] = $token['create_time'] + $token['expires_in'];
    $token['sys_ip'] = isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'0.0.0.0';

    //写入token表
//    $res = get_curl('login', '/token/add', $token);
    \think\Db::name('token')->insert($token);
    return $token_str;
}


/**
 * 通过token获取用户id
 * @param $token  token
 */
function getIdByToken($token)
{
    $paginate_map = [];
    $select_res = '';
    if (!($token===null||$token==''||$token=='%%')){
       $v =[['token','=',$token]];
        array_push($paginate_map,$v);
        $select_res=Db::connect("mysql://root:root@127.0.0.1:3306/zb_login#utf8")->table('tp_token')->where($paginate_map)->paginate();
    }
    return $select_res;
}

/**
 * 通过id获取用户q权限
 * @param $token  token
 */
function getRoleByid($id)
{
    $paginate_map = [];
    $select_res = '';
    if (!($id===null||$id==''||$id=='%%')){
        $v =[['account_id','=',$id]];
        array_push($paginate_map,$v);
        $select_res=Db::connect("mysql://root:root@127.0.0.1:3306/zb_admin_auth#utf8")
            ->field('a.*,b.name,b.role')
            ->table('tp_shop_admin_role a ')
            ->leftjoin('tp_shop_role b','a.shop_role_id=b.id')
            ->where($paginate_map)
            ->paginate();
    }
    return $select_res;
}

//字段tinyint 1转true 0转false
function tobool(&$list, $columns)
{
    foreach ($list as $key => $item) {
        foreach ($columns as $column) {
            if ($list[$key][$column]) {
                $list[$key][$column] = true;
            } else {
                $list[$key][$column] = false;
            }
        }
    }
}

/**
 * 通过account_id或openid获取用户信息
 */
function account($openId)
{
    $account = Db::table('zb_login.tp_account')
        ->where('openId', $openId)
        ->whereOr('id', $openId)
        ->find();

    if (!$account){
        return $account;
    }
    $res = [
        'account_id' => $account['id'],
        'account_name' => $account['account_name'],
        'islock' => $account['islock']
    ];
    if($account){
        $user = Db::table('zb_user.tp_user')
            ->where('account_id', $account['id'])
            ->find();
        if ($user){
            $res = array_merge($res,$user);
        }
    }

    return $res;
}


/**
 * 获取当前页面完整URL地址
 */
function get_url() {
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
    return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
}

function get_host(){
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') ;
}

/**
 * 记录log
 */
function logs($name, $data) {
    file_put_contents(\think\facade\Env::get('root_path') . 'log/' . $name . "_log.txt", var_export($data, TRUE), FILE_APPEND);
    file_put_contents(\think\facade\Env::get('root_path') . 'log/' . $name . "2_log.txt", print_r($data, TRUE), FILE_APPEND);
    file_put_contents(\think\facade\Env::get('root_path') . 'log/' . $name . "_log.txt", "\r\n", FILE_APPEND);
    file_put_contents(\think\facade\Env::get('root_path') . 'log/' . $name . "2_log.txt", "\r\n", FILE_APPEND);
}

/**
 *  日志数据同步接口
 * @param  string $name [日志名称]
 * @param  array,string $content [日志内容]
 * @param  array $config [系统,模块,方法]
 */
function synchronize_log($name, $content, $config = [])
{
    //处理数据
    $data = [];
    $data['name'] = $name;
    $data['content'] = var_export($content, True);
    $data['token'] = 'WarYgMkUjEhKCIo41zSG';
    $data['system'] = isset($config['system']) ? $config['system'] : Config()['app']['project_name'];
    $data['module'] = isset($config['module']) ? $config['module'] : Request::module();
    $data['func'] = isset($config['func']) ? $config['func'] : Request::action();
    //发送post http 请求
    $url = Config()['app']['log_http'];
//    $data = post_curls($url, $data);
    $data = \tools\curl\Curl::post($url, $data);
    return $data;
}

/**
 * POST请求https接口返回内容
 * @param  string $url [请求的URL地址]
 * @param  string $post [请求的参数]
 * @return  string
 */
function post_curls($url, $post)
{
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post); // Post提交的数据包
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    $res = curl_exec($curl); // 执行操作
    if (curl_errno($curl)) {
        echo 'Errno' . curl_error($curl);//捕抓异常
    }
    curl_close($curl); // 关闭CURL会话
    return $res; // 返回数据，json格式
}

/**
 * POST请求https接口返回内容
 * @param  string $url [请求的URL地址]
 * @param  string $post [请求的参数]
 * @return  string
 */
function pdo_sql($url, $post)
{
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post); // Post提交的数据包
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    $res = curl_exec($curl); // 执行操作
    if (curl_errno($curl)) {
        echo 'Errno' . curl_error($curl);//捕抓异常
    }
    curl_close($curl); // 关闭CURL会话
    return $res; // 返回数据，json格式

}

/**
 * xml转换成json
 */
function xml_to_json($source) {
    if(is_file($source)){
        $xml_array=simplexml_load_file($source);
    }else{
        $xml_array=simplexml_load_string($source);
    }
    $json = json_encode($xml_array);
    return $json;
}
function get_user($id,$type="u"){
    if($type=="u"){
        return get_user_by_id($id);
    }else if($type=="m"){
        return get_merchant_admin_by_id($id);
    }if($type=="a"){
        return get_admin_by_id($id);
    }
}

//根据id用户信息
function get_user_by_id($id){
    $data = get_curl("user","user/get_user_by_id",array('id'=>$id));

    //加了判真的判断
    if(isset($data['status']) &&!empty($data['status'])){
        $user_info['account_id']=$data['data']['id'];
        $user_info['nickname']=$data['data']['nickName'];
        $user_info['logo']=$data['data']['avatarUrl'];
        $user_info['phone']=$data['data']['phone'];
        $user_info['merchant_id']=$data['data']['merchantID'];
        $user_info['status']=$data['data']['status'];
        $user_info['account_type']="u";
        return $user_info;
    }else{
        return [];
    }
}
//根据id商家管理员信息
function get_merchant_admin_by_id($id){
    $data=get_curl("merchant","admin_user/info",array('id'=>$id));
    if(isset($data['status'])&&!empty($data['status'])){
        $user_info['account_id']=$data['data']['id'];
        $user_info['nickname']=$data['data']['nickname'];
        $user_info['logo']=$data['data']['head_img'];
        $user_info['phone']=$data['data']['phone'];
        $user_info['status']=$data['data']['status'];
        $user_info['merchant_id']=$data['data']['merchant_id'];
        $user_info['account_type']="m";
        return $user_info;
    }else{
        return [];
    }
}

//根据管理员信息
function get_admin_by_id($id){
    $data=get_curl("user","admin_user/info",array('id'=>$id));
    if(isset($data['status'])&&!empty($data['status'])){
            $user_info=[];
            $user_info['account_id']=$data['data']['id'];
            $user_info['nickname']=$data['data']['nickname'];
            $user_info['logo']=$data['data']['head_img'];
            $user_info['phone']=$data['data']['phone'];
            $user_info['status']=$data['data']['status'];
            $user_info['account_type']="a";
        return $user_info;
    }else{
        return [];
    }
}

function get_member_list($map,$type="u"){
    if($type=="u"){
        return get_user_list($map);
    }else if($type=="m"){
        return get_merchant_admin_list($map);
    }if($type=="a"){
        return get_admin_list($map);
    }
}


//获取用户列表
function get_user_list($map){
    $data=get_curl("user","user/get_select",$map);
    if(isset($data['list'])){
        $user_infos=[];
        foreach ($data['list'] as $user){
            $user_info['account_id']=$user['id'];
            $user_info['nickname']=$user['nickName'];
            $user_info['logo']=$user['avatarUrl'];
            $user_info['phone']=$user['phone'];
            $user_info['merchant_id']=$user['merchantID'];
            $user_info['status']=$user['status'];
            $user_info['account_type']="u";
            $user_infos[]=$user_info;
        }

        return $user_infos;
    }else{
        return [];
    }
}
//获取商家管理员列表
function get_merchant_admin_list($map){
    if(isset($map['page'])){
        $map['page']=1;
    }
    if(isset($map['page'])){
        $map['pagesize']=1000;
    }
    $data=get_curl("merchant","admin_user/get_admin",$map);
    if(isset($data['data'])){
        $user_infos=[];
        foreach ($data['data'] as $admin) {
            $user_info=[];
            $user_info['account_id'] = $admin['id'];
            $user_info['nickname'] = $admin['nickname'];
            $user_info['logo'] = $admin['head_img'];
            $user_info['phone'] = $admin['phone'];
            $user_info['status'] = $admin['status'];
            $user_info['merchant_id'] = $admin['merchant_id'];
            $user_info['account_type'] = "m";
            $user_infos[]=$user_info;
        }
        return $user_infos;
    }else{
        return [];
    }
}
//根据管理员信息
function get_admin_list($map){
    $data=get_curl("user","admin_user/get_list",$map);
    if(isset($data['list'])){
        $user_infos=[];
        foreach ($data['list'] as $admin){
            $user_info['account_id']=$admin['id'];
            $user_info['nickname']=$admin['nickname'];
            $user_info['logo']=$admin['head_img'];
            $user_info['phone']=$admin['phone'];
            $user_info['status']=$admin['status'];
            $user_info['account_type']="a";
            $user_infos[]=$user_info;
        }
        return $user_infos;
    }else{
        return [];
    }
}